//导入request.ts请求服务
import request from '../utils/request.ts'

// 商品接口类型定义
export interface Product {
  id: number;
  merchantId: number;
  name: string;
  price: number;
  image: string;
  stock: number; //库存
  category: string;
  isUserAddCategory: number; //是否用户添加分类
  brand: string; //品牌
  spec: string; //规格
  sold: number; //销量
  commentCount?: number; // 评论数（后端可能返回）
  score?: number; // 平均评分（来自后端 item.score）
  status: number; //状态
  createTime: string; //创建时间
  updateTime: string; //更新时间
}

//分页查询首页商品接口，只有一个页码参数
export const getProductsService = (pageNum: number) => {
  return request.get('/item/findHomeItems', {
    params: {
      pageNum
    }
  })
}

// 根据分类获取商品
export const getProductsByCategoryService = (category: string) => {
  return request.get(`/products/category/${category}`)
}

//根据商品id查询商品
export const getProductDetailsService = (id: number) => {
  return request.get(`/item/findById?id=${id}`)
}

// 搜索商品
export const searchProductsService = (keyword: string, searchAfter: string, direction: string) => {
  const params: any = {
    keyword: encodeURIComponent(keyword),
    direction: encodeURIComponent(direction)
  }

  // 只有当searchAfter不为空时才添加参数
  if (searchAfter && searchAfter.trim()) {
    params.searchAfter = encodeURIComponent(searchAfter)
  }

  // 构建查询字符串
  const queryString = Object.entries(params)
    .map(([key, value]) => `${key}=${value}`)
    .join('&')

  return request.get(`/item/search?${queryString}`)
}

// 添加到购物车
export const addToCartService = (productId: number, quantity: number) => {
  return request.post('/item/addItem', { productId, quantity })
}